<template>
  <div class="table m7fixed">
    <pl-table ref="multipleTable"
              :data="tableData"
              :summary-method="getSummaries"
              show-summary
              row-key="_id"
              size = "mini"
              use-virtual
              :border="false"
              :row-height="30"
              style="width: 100%; overflow-x: auto;"
              showOverflowTooltip="true"
              :thtd-beyond-hiding="false"
              :cell-class-name="computeStyle"
              @selection-change="handleSelectionChange">
      <pl-table-column type="selection" width="55" :reserve-selection="true">
      </pl-table-column>
      <template v-for="item in config">
        <pl-table-column v-if="item.show === true && item.name === 'agentName' && isDrill"
                        :prop="item.name"
                        :border-line="false"
                        :key="item.order"
                        :label="item.displayname"
                        sortable
                        :sort-method="sortMethod(item.name)"
                        :show-overflow-tooltip = "bool">
            <template scope="scope">
              <span class="drill"
                    @click="agentName(scope.row.agentId, scope.row.agentName)">{{scope.row.agentName}}</span></template></pl-table-column>
        <pl-table-column
            v-else-if="item.show === true && item.name !== 'agent_name' && item.name !== 'everyCustomStatusTime'"
            :prop="item.name"
            :key="item.order"
            :label="item.displayname"
            :sort-method="sortMethod(item.name)"
            sortable
            ></pl-table-column>
        <pl-table-column v-else-if="item.show === true && item.name === 'agent_name'"
                        :prop="item.name"
                        :key="item.order"
                        :label="item.displayname"
                        sortable
                        :sort-method="sortMethod(item.name)"
                        :show-overflow-tooltip = "bool">
            <template scope="scope">
              <span class="drill"
                    @click="agentName(scope.row.AgentID, scope.row.agent_name)">{{scope.row.agent_name}}</span></template></pl-table-column>
      </template>
    </pl-table>
  </div>
</template>
<script>
  let timor = null
  let timer = null
  import {cusSort} from '@/utils/reportUtils.js'
  export default {
    name: 'checkboxTable',
    data () {
      return {
        bool: true, // 表格列超出显示点绑定值Bool
        isbool: true, // 默认加载尽量全选执行方法时避免handleSelectionChange执行，临时设置的变量
        multipleTable: [], // table选择列时绑定的列的数据集合
        style: 'width: 100%;', // table绑定样式
        theight: 'fixed', // table绑定高度值
        isResize: true, // 窗口改变时，绑定变量值
        tableData: [],
        remarkArr: [], // 标记得自定义公式集合
        height: 180
      }
    },
    props: {
      isDrill: {
        type: Boolean,
        default: function () {
          return false
        }
      },
      isRemark: {
        type: Boolean,
        default: function () {
          return false
        }
      },
      data: {
        type: Array,
        default: function () {
          return []
        }
      },
      sum: {
        type: Array,
        default: function () {
          return []
        }
      },
      config: {
        type: Array,
        default: function () {
          return []
        }
      }
    },
    methods: {
      dealCount (item, result) {
        let bool = false
        if (item.type === 'minOrSec') {
          let dateArr = result.split(':')
          result = parseInt(dateArr[0]) * 3600 + parseInt(dateArr[1]) * 60 + parseInt(dateArr[2])
        } else {
          result = parseInt(result) || 0
        }
        switch (item.symbol) {
          case '1':
            if (result === item.remarkVal1) {
              bool = true
            }
            break
          case '2':
            if (result !== item.remarkVal1) {
              bool = true
            }
            break
          case '3':
            if (result > item.remarkVal1) {
              bool = true
            }
            break
          case '4':
            if (result < item.remarkVal1) {
              bool = true
            }
            break
          case '5':
            if (result >= item.remarkVal1) {
              bool = true
            }
            break
          case '6':
            if (result <= item.remarkVal1) {
              bool = true
            }
            break
          case '7':
            if (item.remarkVal1 < result && result < item.remarkVal2) {
              bool = true
            }
            break
        }
        return bool
      },
      computeStyle ({row, column, rowIndex, columnIndex}) {
        if (!this.isRemark) {
          return
        }
        // return 'aaaaa'
        let bool = false
        if (column.property && this.remarkArr.includes(column.property)) {
          let curHeader = this.config.filter(item => {
            return item.name === column.property
          })
          bool = this.dealCount(curHeader[0], row[column.property])
        }
        if (bool) {
          return 'remark'
        }
        return ''
      },
      tableStyle (type) {
        if (this.data.length === 0) {
          return
        }
        // 动态计算表格的实际高度和屏幕高度来判断是否表头吸顶
        // tableHeight 表格body(内容)实际高度
        // headerHeight 表格header(表头)实际高度
        // footerHeight 表格footer(合计)实际高度
        // toolHeight 顶部工具条高度 + 三级导航高度 + 30px间距
        // winHeight 浏览器窗口高度
        // if (this.isResize) {
        //   let parentDom = this.$el
        //   if (!parentDom) {
        //     return
        //   }
        //   let parentWidth = parentDom ? parentDom.clientWidth : 0
        //   let tableWidth = tableDom.clientWidth
        //   let headerDom = parentDom.querySelectorAll('.el-table .el-table__header-wrapper .el-table__header')[0]
        //   let headerHeight = headerDom ? headerDom.clientHeight : 0
        //   let footerDom = parentDom.querySelectorAll('.el-table .el-table__footer-wrapper .el-table__footer')[0]
        //   let footerHeight = footerDom ? footerDom.clientHeight : 0
        //   let nav1Dom = document.querySelectorAll('.top-nav')[0]
        //   let nav2Dom = document.querySelectorAll('.right_detail .top_nav')[0]
        //   let toolHeight = (nav1Dom ? nav1Dom.clientHeight : 0) + (nav2Dom ? nav2Dom.clientHeight : 0) + 30
          // let winHeight = document.body.clientHeight
        //   let hollHeight = tableHeight + headerHeight + footerHeight
        //   if (winHeight - toolHeight - hollHeight < 0) { // 浏览器H - 工具条H - 三级导航H - tableH < 0 表示剩余空间放不下全部的table
        //     this.theight = 'fixed' // 饿了么的固定表头API
        //     this.style = 'width: 100%; height: calc(100vh - ' + toolHeight + 'px);' // 固定表头需要确切的表格高度
        //   } else {
        //     this.theight = '' // 不需要表头固定
        //     this.style = 'width: 100%;'
        //   }
        //   if (footerDom) {
        //     let lastWidth = parentWidth - tableWidth
        //     if (lastWidth > 10) { // 外层-内层宽度不大于纵向滚动条的宽度时说明没有横向滚动条，合计要贴住底部
        //       footerDom.parentNode.style.height = '34px'
        //       footerDom.parentNode.style.marginTop = '8px'
        //     } else if (lastWidth < 0) { // 有横向滚动条
        //       footerDom.parentNode.style.height = '40px'
        //       footerDom.parentNode.style.marginTop = '0px'
        //     } else { // 无横向滚动条
        //       footerDom.parentNode.style.height = '36px'
        //       footerDom.parentNode.style.marginTop = '8px'
        //     }
        //   }
        // }
        let parentDom = this.$el
        let headerDom = parentDom.querySelectorAll('.el-table .el-table__header-wrapper .el-table__header')[0]
        let bodyWrapper = parentDom.querySelectorAll('.el-table .el-table__body-wrapper')[0]
        let headerHeight = headerDom ? headerDom.clientHeight : 0
        if (headerHeight && this.data.length !== 0) {
          let headH = 166 + headerHeight + 'px'
          bodyWrapper.style.maxHeight = 'calc(100vh - ' + headH + ')'
        }
      },
      // 向父组件传递座席id和名称
      agentName (id, name) {
        this.$emit('agentName', id, name)
      },
      // 自定义的排序方法
      // 数字直接排序
      // String时分秒形式以：分隔转数字排序
      // String带 % s 转浮点数排序
      // 剩下中文用这个localeCompare排序
      sortMethod (name) {
        return cusSort(name)
      },
      // 实现checkBox全选
      toggleSelection (rows) {
        if (rows) {
          this.isbool = false
          this.$refs.multipleTable.clearSelection()
          this.$refs.multipleTable.toggleAllSelection()
          rows.forEach(row => {
            // this.$refs.multipleTable.toggleRowSelection(row)
            this.multipleTable.push(row)
          })
          this.isbool = true
        }
      },
      debounce() {
        if (timer) clearTimeout(timer)
        // 节流避免多次重绘
        timer = setTimeout(() => {
          this.tableStyle()
        }, 500)
      },
      // 自定义合计方法 返回合计数据
      getSummaries () {
        let sums = ['']
        let i = 0
        this.config.map((item, index) => {
          if (item.show && item.name !== 'everyCustomStatusTime') {
            i++
            sums[i] = this.sum[0][item.name] ? this.sum[0][item.name] : 0
          }
        })
        return [sums]
      },
      // checkbox勾选时向父级传递 参数: 已勾选数据列数据
      handleSelectionChange (val) {
        if (this.isbool) {
          this.$emit('tellme', val, 1)
        }
      }
    },
    watch: {
      // 计算出需要标记得表头
      config (cur) {
        cur.forEach(item => {
          if (item.remark) {
            this.remarkArr.push(item.name)
          }
        })
      },
      // 监测数据变化执行table全选和处理表头自适应
      data (cur) {
        let num = 50
        let self = this
        clearInterval(timor)
        // 数据大于200条采用分批次渲染 否则 直接渲染
        if (cur.length > 200) {
          timor = setInterval(function () {
            if (num > cur.length || num === cur.length) {
              // 避免数据缺失
              self.tableData = cur
              self.toggleSelection(self.tableData)
              clearInterval(timor)
              return
            }
            // 数据截取赋值渲染
            let sliceData = cur.slice(0, num)
            self.tableData = sliceData
            if (num === 50) {
              // 先让数据前五十条多选勾上 和 计算表格自适应高度
              self.toggleSelection(self.tableData)
              self.$nextTick(function () {
                setTimeout(function () {
                  self.tableStyle()
                }, 100)
              })
            }
            // 每次多渲染 80 条数据
            if (cur.length > 2000) {
              num += 200
            } else {
              num += 80
            }
          }, 100)
        } else {
          this.tableData = cur
          self.toggleSelection(this.tableData)
          self.$nextTick(function () {
            setTimeout(function () {
              self.tableStyle()
            }, 100)
          })
        }
      }
    },
    mounted () {
      let self = this
      // 初始化监听事件
      window.addEventListener('resize', self.debounce)
    },
    activated () { // 在别的模块缩放了窗口回来的时候要触发一下重新计算
      let self = this
      if (!this.isResize) {
        self.debounce()
        window.addEventListener('resize', self.debounce)
      }
      this.isResize = true
    },
    deactivated () { // 离开后在别的模块缩放窗口不触发tableStyle()
      let self = this
      this.isResize = false
      window.removeEventListener('resize', self.debounce)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .drill
    color $c-main
    cursor pointer
  .el-table td.aaa .cell
    color #f00
</style>
